package com.boot2.core.ueditor;

import com.boot2.core.conf.UploadUrlConf;
import com.boot2.core.utils.MultipartFileUtil;
import com.boot2.core.utils.upload.FileUploadUtil;
import com.boot2.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: hobbesgo
 * @Description:
 * @Date: 创建于 14:54 2018/1/11 0011
 * @Modified By:
 */
//@Controller
public class UEditorBaseController extends BaseController {

    @Autowired
    UploadUrlConf uploadUrlConf;

    /**
     * ueditor一次实际只会上传一张图片
     *
     * @param upfile
     * @return
     */
//    @RequestMapping(value = "/ueditor")
    @ResponseBody
    public Object ueditor(MultipartFile[] upfile) {
//        System.out.println("upfile = " + upfile);
        String rootPath = session().getServletContext().getRealPath("/");
        if (null == upfile) {
            String exec = new ActionEnter(request(), rootPath).exec();
            return exec;
        } else {
            List<String> fileList = FileUploadUtil.uploadFiles2Oss(upfile, "ueditor/");
            String url = fileList.get(0);

            //上传返回如: exec = {"state": "SUCCESS","original": "aa_20190605115106.jpg","size": "98344","title": "1559919343534093692.jpg","type": ".jpg","url": "/image/20190607/1559919343534093692.jpg"}
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("state", "SUCCESS");
            resultMap.put("original", MultipartFileUtil.getOriginalFilename(upfile[0]));
            resultMap.put("size", MultipartFileUtil.getSize(upfile[0]) + "");
            resultMap.put("title", MultipartFileUtil.getOriginalFilename(upfile[0]));
            resultMap.put("type", MultipartFileUtil.getSuffix(upfile[0]));
            resultMap.put("url", uploadUrlConf.getEndPoint() + "/" + url);
            return resultMap;
        }
//        try {
//            String exec = new ActionEnter(request(), rootPath).exec();
//            System.out.println("exec = " + exec);
//            PrintWriter writer = response().getWriter();
//            writer.write(exec);
//            writer.flush();
//            writer.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

}
